<template>
  <FPage>
    <template #header>
      <div style="padding: 5px">
        <el-tree-select
          style="width: 100%"
          v-model="selectedUnit"
          :data="unitTree" default-expand-all
          check-strictly node-key="id"
          :props="defaultProps"
          @change="loadGroups"
          :render-after-expand="false"
        />
      </div>
    </template>
    <FListV2
      :selected-key="selectedKey"
      title-name="groupName"
      @select="select" size="small"
      @doubleClick="createGroupSelection"
      :data-source="groups"/>
  </FPage>
</template>

<script setup>
import {getAction} from '@/request/BaseRequest';
import {UserConfig} from '@/components/UserSelectorModal/DefaultUserConfig';
import {guid, isEmpty, listToTrees, real} from '@/utils/CommonUtils';
import {onMounted, shallowRef} from 'vue';
import FListV2 from '@/components/FListV2/index.vue';
import FPage from '@/components/layout/FPage.vue';
import {useStore} from 'vuex';

const store = useStore();
const unitTree = shallowRef([]);
const selectedUnit = shallowRef();
const selectedKey = shallowRef();
const groups = shallowRef([]);
const loading = shallowRef(false);
const emits = defineEmits(['create']);
let userInfo = undefined;
const defaultProps = {
  children: 'children',
  label: 'unitName',
};

onMounted(() => {
  userInfo = real(store.getters['user/userInfo']);
  selectedUnit.value = userInfo.unitId;
  loadGroups();
  loadUnits();
});

function loadUnits() {
  getAction('/sys/unit/loadUnits').then(data => {
    if (data.success) {
      let result = data.result;
      setUnitTree(result);
    }
  });
}

function setUnitTree(list) {
  if (isEmpty(list)) list = [];
  unitTree.value = listToTrees(list);
}

function select(group) {
  selectedKey.value = real(group).id;
}

function loadGroups() {
  loading.value = true;
  getAction('/base/baseGroup/query', {
    unitId: selectedUnit.value
  }).then(data => {
    loading.value = false;
    if (data.success) {
      groups.value = data.result;
    }
  });
}

function createGroupSelection(group) {
  let res = JSON.parse(JSON.stringify(UserConfig));
  res.type = 'group';
  res.groupId = group.id;
  res.groupName = group.groupName;
  res.configName = group.groupName;
  res.id = guid();
  emits('create', res);
}
</script>
<style scoped>

</style>
